package com.gack.netty.encoderAndDecoder.decoder;

import java.util.List;

import com.gack.netty.encoderAndDecoder.constract.SerialConstract;
import com.gack.netty.proto.MessageModule.Message;
import com.gack.netty.proto.MessageModule.Message.Builder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

/**
 * 
* @ClassName: MyDecoder 
* @Description: TODO(自定义解码器) 
* @author (ZhangXinYu)  
* @date 2018年9月6日 下午3:05:21 
* @version V1.0
 */
public class MyDecoder extends ByteToMessageDecoder{

	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		// 可读字节少于8为 数据不全 继续等待数据接收
		if(in.readableBytes() < 8){
			return;
		}
		
		int beginReader = in.readerIndex();
		while(true){
			// 读取到包头
			if(in.readInt() == SerialConstract.PACKAGE_HEADER){
				break;
			}
		}
		
		// 数据长度
		int length = in.readInt();
		
		// 可读长度少于数据长度  数据不全  继续等待数据接收
		if(in.readableBytes() < length){
			in.readerIndex(beginReader);
			return;
		}
		
		//读取数据
		ByteBuf dataBuf = in.readBytes(length);
		Builder builder = Message.newBuilder();
		builder.setMsgType(dataBuf.readInt());
		int contentLength = dataBuf.readInt();
		builder.setContent(dataBuf.readBytes(contentLength).toString(CharsetUtil.UTF_8));
		builder.setTimestamp(dataBuf.readLong());
		int equipmentLength = dataBuf.readInt();
		builder.setEquipment(dataBuf.readBytes(equipmentLength).toString(CharsetUtil.UTF_8));
		
		out.add(builder.build());
	}
}
